package com.zmn.oms.dubbo.impl.channel;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.oms.common.constant.OmsErrorCodeConsts;
import com.zmn.oms.common.dio.channel.ChannelApiExtraData;
import com.zmn.oms.common.dio.channel.ChannelApiOrderWorkAddDIO;
import com.zmn.oms.common.dio.normal.orderadd.OrderProductDIO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.dubbo.dto.zmn.order.NewOrderDRO;
import com.zmn.oms.dubbo.interfaces.channel.ChannelApiOrderWorkRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.dto.factory.OrderFactoryDTO;
import com.zmn.oms.model.dto.order.NewOrderExternalShopDTO;
import com.zmn.oms.model.dto.order.zmn.FactoryNewOrderDTO;
import com.zmn.oms.model.dto.order.zmn.OrderExtendDTO;
import com.zmn.oms.model.dto.order.zmn.ZsNormalNewOrderDTO;
import com.zmn.oms.model.dto.product.OrderProductDTO;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.WorkFlowContextBService;
import com.zmn.oms.zmn.normal.business.interfaces.order.FactoryOrderBService;
import com.zmn.oms.zmn.normal.business.interfaces.order.ZsNormalOrderBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

/**
 * 类描述：
 *
 * @author wangxiaokun
 * @since 2021/04/07 18:54
 */
@Slf4j
@Service(loadbalance = "roundrobin", timeout = 20000, retries = 0, version = DubboConsts.INTERFACE_VERSION, validation = "true")
public class ChannelApiOrderWorkRemoteServiceImpl implements ChannelApiOrderWorkRemoteService {

    @Autowired
    protected ZsNormalOrderBService zsNormalOrderBService;
    @Autowired
    private FactoryOrderBService factoryOrderBService;
    @Autowired
    private WorkFlowContextBService workFlowContextBService;

    @Override
    public ResponseDTO<NewOrderDRO> addOrder(ChannelApiOrderWorkAddDIO channelApiOrderWorkAddDIO) {
        log.info("渠道接口下单===》入参[{}]", JSON.toJSONString(channelApiOrderWorkAddDIO));

        try {
            // 厂商录单，或者普通录单
            if (Objects.isNull(channelApiOrderWorkAddDIO.getFactoryId())) {

                // 基础信息
                ZsNormalNewOrderDTO dto = BeanMapper.map(channelApiOrderWorkAddDIO, ZsNormalNewOrderDTO.class);
                dto.setIp(channelApiOrderWorkAddDIO.getOperatorIP());
                // 订单信息
                BeanMapper.copy(channelApiOrderWorkAddDIO.getOrderWorkBaseDIO(), dto);
                // 产品信息
                OrderProductDTO orderProductDTO = BeanMapper.map(channelApiOrderWorkAddDIO.getOrderProductDIO(), OrderProductDTO.class);
                dto.setOrderProductList(Lists.newArrayList(orderProductDTO));
                // 用户信息
                BeanMapper.copy(channelApiOrderWorkAddDIO.getUserDIO(), dto);
                dto.setUserName(StringUtils.defaultString(channelApiOrderWorkAddDIO.getUserDIO().getContactName(), channelApiOrderWorkAddDIO.getUserDIO().getUserName()));
                // 扩展信息
                OrderExtendDTO orderExtendDTO = BeanMapper.map(channelApiOrderWorkAddDIO.getChannelApiExtraData(), OrderExtendDTO.class);
                dto.setOrderExtend(orderExtendDTO);
                ChannelApiExtraData apiExtraData = channelApiOrderWorkAddDIO.getChannelApiExtraData();
                BeanMapper.copy(apiExtraData, dto);
                dto.setChannelLoginPhone(apiExtraData.getLoginPhone());

                // 外部店铺
                if (Objects.nonNull(channelApiOrderWorkAddDIO.getExternalShopInfo())) {
                    NewOrderExternalShopDTO externalShopDTO = new NewOrderExternalShopDTO();
                    externalShopDTO.setExternalShopId(channelApiOrderWorkAddDIO.getExternalShopInfo().getExternalShopId());
                    externalShopDTO.setInternalShopId(channelApiOrderWorkAddDIO.getExternalShopInfo().getInternalShopId());
                    externalShopDTO.setInternalShopName(channelApiOrderWorkAddDIO.getExternalShopInfo().getInternalShopName());
                    externalShopDTO.setInternalBranchShopName(channelApiOrderWorkAddDIO.getExternalShopInfo().getInternalBranchShopName());
                    dto.setExternalShopInfo(externalShopDTO);
                }

                OrderBO orderBO = zsNormalOrderBService.insertChannelOrder(dto);

                NewOrderDRO newOrderDRO = new NewOrderDRO();
                newOrderDRO.setWorkId(orderBO.getOrderWork().getWorkId());
                newOrderDRO.setOrderId(orderBO.getOrderWork().getOrderId());
                newOrderDRO.setUserId(orderBO.getOrderWork().getUserId());
                log.info("添加订单返回：{}", newOrderDRO);

                if (Objects.equals(apiExtraData.getAutoFlow(), true)) {
                    // 工单自动流转
                    workFlowContextBService.asyncAutoFlow(orderBO.getOrderWork().getOrderId(), orderBO.getOrderWork().getWorkId());
                }

                return ResponseDTO.success(newOrderDRO, "OK");

            } else {
                // 基础信息
                FactoryNewOrderDTO dto = BeanMapper.map(channelApiOrderWorkAddDIO, FactoryNewOrderDTO.class);
                BeanMapper.copy(channelApiOrderWorkAddDIO.getOrderWorkBaseDIO(), dto);
                dto.setIp(channelApiOrderWorkAddDIO.getOperatorIP());
                // 用户信息
                BeanMapper.copy(channelApiOrderWorkAddDIO.getUserDIO(), dto);
                // 厂商信息
                OrderFactoryDTO factoryDTO = new OrderFactoryDTO();
                OrderProductDIO orderProductDIO = channelApiOrderWorkAddDIO.getOrderProductDIO();
                factoryDTO.setFactoryId(channelApiOrderWorkAddDIO.getFactoryId());
                factoryDTO.setProductId(orderProductDIO.getProductId());
                factoryDTO.setFcProductNumber(orderProductDIO.getNumber());
                factoryDTO.setFaultIdList(orderProductDIO.getFaultIdList());
                factoryDTO.setRemark(orderProductDIO.getRemark());
                dto.setOrderFactory(factoryDTO);
                // 渠道信息
                BeanMapper.copy(channelApiOrderWorkAddDIO.getChannelApiExtraData(), dto);
                OrderExtendDTO orderExtendDTO = BeanMapper.map(channelApiOrderWorkAddDIO.getChannelApiExtraData(), OrderExtendDTO.class);
                dto.setOrderExtend(orderExtendDTO);

                OrderBO orderBO = factoryOrderBService.insertChannelOrder(dto);

                OrderWork orderWork = orderBO.getOrderWork();
                NewOrderDRO newOrderDRO = new NewOrderDRO();
                newOrderDRO.setWorkId(orderWork.getWorkId());
                newOrderDRO.setOrderId(orderWork.getOrderId());
                log.info("添加订单返回：{}", newOrderDRO);

                if (Objects.equals(channelApiOrderWorkAddDIO.getChannelApiExtraData().getAutoFlow(), true)) {
                    // 工单自动流转
                    workFlowContextBService.asyncAutoFlow(orderBO.getOrderWork().getOrderId(), orderBO.getOrderWork().getWorkId());
                }

                return ResponseDTO.success(newOrderDRO, "OK");
            }
        } catch (OmsBaseException e) {
            log.error("订单保存错误:{}，错误码[{}]", e.getMessage(), e.getCode(), e);
            if (Objects.nonNull(e.getCode()) && e.getCode() > OmsErrorCodeConsts.MIN_CODE) {
                return ResponseDTO.fromErrorCodeTable(e.getCode());
            }
            return ResponseDTO.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("订单保存错误:{}", e.getMessage(), e);
            return ResponseDTO.fail(e.getMessage());
        }
    }
}
